package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.domain.Identity;
import org.example.domain.bean.LoginRequest;
import org.example.domain.bean.RestResponse;
import org.example.service.IIdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

@Api(tags = "登录管理接口")
@RestController
public class LoginController {

    @Autowired
    private IIdentityService iIdentityService;

    @ApiOperation(value = "登陆之后返回token")
    @PostMapping("/login")
    public RestResponse<Map<String,String>> login(@RequestBody LoginRequest loginRequest, HttpServletRequest request){
        return iIdentityService.login(loginRequest,request);
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/identity/info")
    public RestResponse<Identity> getIdentityInfo(Principal principal){
        if(null == principal){
            return null;
        }
        String username = principal.getName();
        Identity identity = iIdentityService.getIdentityByUserName(username);
        identity.setPwd(null);
        identity.setRoles(iIdentityService.getRoles(identity.getId()));
        return RestResponse.success(identity);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RestResponse logout(){
        return RestResponse.success("注销成功!");
    }
}
